package cn.open.feishu.alert.support;

import cn.open.feishu.alert.common.utils.Md5Util;
import cn.open.feishu.alert.config.FeiShuProperties;
import com.google.common.cache.Cache;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 告警次数累计计数器本地缓存
 * @Author fandy.lin
 * @Date 2021/11/11 1:58 下午
 **/
@Data
@Slf4j
@AllArgsConstructor
public class CounterNativeCache {
    private FeiShuProperties feiShuProperties;
    private Cache<String, Integer> cache;

    /**
     * 判断当前格式告警聚集是否满足条件
     *
     * @param pattern
     * @return
     */
    public Boolean isIncrCountLimit(String pattern) {
        String encode = Md5Util.getEncode(pattern);
        synchronized (cache) {
            Integer count = getCount(encode);
            //pattern计数时间范围内首次,可以触发告警
            if (count == null) {
                cache.put(encode, 1);
                return true;
            }
            //pattern计数聚集达到配置次数触发告警
            if (count + 1 >= feiShuProperties.getCacheCountLimit().intValue()) {
                cache.put(encode, 0);
                return true;
            } else {
                log.info("feishu alert:pattern={},count={}", pattern, count);
                cache.put(encode, count + 1);
                return false;
            }
        }
    }

    private Integer getCount(String encode) {
        Integer count = cache.getIfPresent(encode);
        return count;
    }

}